/*
 * @Description: 流程配置组件
 * @Author: DHL
 * @Date: 2022-12-23 13:52:43
 * @LastEditors: DHL
 * @LastEditTime: 2024-02-07 09:23:37
 */

import { defineComponent } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  apiActReModelCopy,
  apiActReModelDeploy,
  apiActReModelGetByKey,
  apiActReModelSave,
  apiActReModelUpdateById
} from '@/api/flow/actReModel'
import { assign, cloneDeep } from 'lodash-es'
import { ActReModelModel } from '@/api/flow/model/actReModelModel'
import { arrayLastValue } from '@/utils/arrayUtils'
import { apiFlowCategorySearchTree } from '@/api/flow/flowCategory'
import { log } from '@/utils/logUtils'
import selectIcon from '@/icons/iconPreview.vue'
import flowModelDesigner from '@/pages/flow/components/flowDesigner.vue'
import { isEmpty } from '@/utils/isUtils'

export default defineComponent({
  name: 'TwFlowConfig',
  components: { selectIcon, flowModelDesigner },
  props: {},
  emits: ['submit'],
  setup(props, { emit, expose }) {
    /**
     * 显示弹框
     */
    const visible = ref(false)

    const loading = ref(false)

    /**
     * 选中的页签
     */
    const activeName = ref('basics')

    /**
     * 流程参数
     */
    let flowParams: any = {}

    const title = ref('')

    //////////////////////////////////////////////////
    // 函数
    //////////////////////////////////////////////////

    /**
     * 打开弹框
     */
    function handleOpen(params: any) {
      visible.value = true
      flowParams = params
      handleSearchTree()
      handleSearch()
    }

    /**
     * 关闭弹框
     */
    function handleClose() {
      visible.value = false
      emit('submit')
    }

    //////////////////////////////////////////////////
    // 基础信息
    //////////////////////////////////////////////////
    const dbFormRef = ref()

    /**
     * 表单操作标记
     */
    const action = ref('add')

    /**
     * 公共
     */
    const state = reactive({ category: '' })

    const defaultForm = {
      name: '', // 名称
      key: '', // 标识
      category: '', // 分类
      description: '', // 描述
      icon: '' // 图标
    }

    let dbForm = reactive<ActReModelModel>(cloneDeep(defaultForm))

    /**
     * 表单验证规则
     */
    const rules = reactive({
      name: [
        {
          required: true,
          message: '请输入名称',
          trigger: 'blur'
        },
        {
          max: 255,
          message: '最多可输入255个字符',
          trigger: 'blur'
        }
      ],
      key: [
        {
          required: true,
          message: '请输入唯一编码',
          trigger: 'blur'
        },
        {
          max: 255,
          message: '最多可输入255个字符',
          trigger: 'blur'
        }
      ],
      category: [
        {
          required: true,
          message: '请输入分类',
          trigger: 'blur'
        },
        {
          max: 255,
          message: '最多可输入255个字符',
          trigger: 'blur'
        }
      ],
      createTime: [
        {
          required: true,
          message: '请选择创建时间',
          trigger: 'blur'
        }
      ],
      lastUpdateTime: [
        {
          required: true,
          message: '请选择最后更新时间',
          trigger: 'blur'
        }
      ],
      version: [
        {
          required: true,
          message: '请输入版本',
          trigger: 'blur'
        }
      ],
      deploymentId: [
        {
          required: true,
          message: '请输入部署ID',
          trigger: 'blur'
        },
        {
          max: 64,
          message: '最多可输入64个字符',
          trigger: 'blur'
        }
      ]
    })

    /**
     * 提交表单
     */
    function handleSubmit() {
      assign(dbForm, {
        category: arrayLastValue(state.category)
      })

      dbFormRef.value.validate((valid: boolean) => {
        if (valid) {
          if (action.value === 'add') {
            addFun()
          } else {
            editFun()
          }
        } else {
          log.warn('流程设计模型部署表', '表单校验失败')
        }
      })
    }

    /**
     * 新增
     * @param isContinue 是否新增并继续
     */
    function addFun() {
      loading.value = true
      apiActReModelSave(dbForm)
        .then((result) => {
          if (result?.success) {
            ElMessage.success(result.message)
            handleSearch()
          } else {
            ElMessage.error(result?.message)
          }
        })
        .catch(() => {})
        .finally(() => {
          loading.value = false
        })
    }

    /**
     * 编辑
     * @returns
     */
    function editFun() {
      loading.value = true
      apiActReModelUpdateById(dbForm)
        .then((result) => {
          if (result?.success) {
            ElMessage.success(result.message)
            handleSearch()
          } else {
            ElMessage.error(result?.message)
          }
        })
        .catch(() => {})
        .finally(() => {
          loading.value = false
        })
    }

    /**
     * 根据流程KEY查询详情
     */
    function handleSearch() {
      loading.value = true
      apiActReModelGetByKey(flowParams.key)
        .then((result) => {
          if (result?.success) {
            const data = result.data
            action.value = 'edit'
            assign(dbForm, { name: flowParams.name, key: flowParams.key }, cloneDeep(data))
            state.category = dbForm.category

            title.value = `${data.categoryName}： ${data.name}（${data.key}）v${data.version}`

            handleInitModelDesigner()
          } else {
            assign(dbForm, { name: flowParams.name, key: flowParams.key })
            action.value = 'add'
          }
        })
        .finally(() => {
          loading.value = false
        })
    }

    /**
     * 流程复制
     * @param row
     */
    function handleCopy() {
      if (isEmpty(dbForm.id)) {
        ElMessage.warning('请先保存基础信息')
        return
      }

      loading.value = true
      apiActReModelCopy(dbForm.id)
        .then((result) => {
          if (result?.success) {
            ElMessage.success(result.message)
            handleSearch()
          } else {
            ElMessage.error(result?.message)
          }
        })
        .catch(() => {})
        .finally(() => {
          loading.value = false
        })
    }
    /**
     * 流程部署
     */
    function handleDeploy() {
      ElMessageBox.confirm(`是否发布流程?`, '流程提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          if (dbForm.id) {
            loading.value = true
            apiActReModelDeploy(dbForm.id)
              .then((result) => {
                if (result?.success) {
                  ElMessage.success(result.message)
                  handleClose()
                } else {
                  ElMessage.error(result?.message)
                }
              })
              .catch(() => {})
              .finally(() => {
                loading.value = false
              })
          }
        })
        .catch(() => {
          ElMessage.info('流程发布被取消了')
        })
    }

    //////////////////////////////////////////////////
    // 流程分类树
    //////////////////////////////////////////////////

    const treeData = ref()

    /**
     * 查询流程分类树
     */
    function handleSearchTree() {
      apiFlowCategorySearchTree({}).then((result) => {
        treeData.value = result.treeData
      })
    }

    //////////////////////////////////////////////////
    // icon
    //////////////////////////////////////////////////

    const selectIconRef = ref()

    /**
     * 选择图标回调
     */
    function handleOpenIcon() {
      selectIconRef.value.handleOpen()
    }

    /**
     * 选择图标回调
     */
    function handleSelectIcon(iconNameParam: string) {
      dbForm.icon = iconNameParam
    }

    //////////////////////////////////////////////////
    // 流程设计
    //////////////////////////////////////////////////
    const flowModelDesignerRef = ref()

    /**
     * 初始化流程设计器
     */
    function handleInitModelDesigner() {
      flowModelDesignerRef.value.handleInit(dbForm.id)
    }

    //////////////////////////////////////////////////
    // 暴露出去，父组件才可以调用到
    //////////////////////////////////////////////////
    expose({
      handleOpen
    })

    return {
      visible,
      loading,
      state,
      handleClose,
      activeName,
      treeData,
      dbForm,
      dbFormRef,
      rules,
      selectIconRef,
      handleOpenIcon,
      handleSelectIcon,
      handleSubmit,
      title,
      handleCopy,
      flowModelDesignerRef,
      handleDeploy
    }
  }
})
